package com.luna.servlets;

import com.luna.beans.Book;
import com.luna.service.BookService;
import com.luna.serviceImpl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(
        name = "RedirectToBookInfo",
        urlPatterns = "/RedirectToBookInfo"
)
public class RedirectToBookInfo extends HttpServlet {

    public RedirectToBookInfo() {}

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html");
        int book_id = Integer.parseInt(req.getParameter("book_id"));
        BookService bookService = new BookServiceImpl();
        Book book = bookService.getBook(book_id);
        if (book != null) {
            req.setAttribute("book", book);
            req.getRequestDispatcher("/book-info.jsp").forward(req, resp);
        } else {
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
        }
    }
}
